﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using AutoWelding.BLL;
using AutoWelding.Models;

namespace AutoWelding.Views.Users
{
    public partial class UserInfoForm : Form
    {
        public UserInfoForm()
        {
            InitializeComponent();
        }
        private UserBLL userBLL = new UserBLL();

        public event Action ReLoadList;//刷新列表页数据

        public AddOrUpdateModel typeModel = null;

        private int userId = 0;//当前修改用户的Id


        private void UserInfoForm_Load(object sender, EventArgs e)
        {
            if (this.Tag != null)
            {
                typeModel = this.Tag as AddOrUpdateModel;
                //初始化 页面信息
                InitUserInfo();
            }
        }

        /// <summary>
        /// 初始化 页面信息
        /// </summary>
        private void InitUserInfo()
        {
            if (typeModel != null)
            {
                if (typeModel.ActType == 1)
                {
                    //新增用户
                    //清空信息
                    ClearInfo();

                }
                else
                {
                    //修改用户信息
                    userId = typeModel.FId;
                    //获取用户信息
                    label_title.Text = "修改用户信息页面";
                    btn_submit.Text = "修改";
                    GetUserInfo(userId);
                }
            }

        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        private void GetUserInfo(int userId)
        {
            UserModel userModel = userBLL.GetUserById(userId);
            txt_username.Text = userModel.UserName;
            txt_nickname.Text = userModel.NickName;
            txt_remark.Text = userModel.Remark;
            int userIdentity = userModel.UserIdentity;
            if (userIdentity == 1)
            {
                radioButton_manage.Checked = true;
            }
            else
            {
                radioButton_noramall.Checked = true;
            }
        }

        /// <summary>
        /// 清空信息
        /// </summary>
        private void ClearInfo()
        {
            txt_nickname.Text = "";
            txt_username.Text = "";
            txt_remark.Text = "";
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_submit_Click(object sender, EventArgs e)
        {
            if (typeModel.ActType == 1)
            {
                //新增
                InsertUser();
            }
            else
            {
                //修改
                UpdateUser();
            }
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void InsertUser()
        {
            string username = txt_username.Text.Trim();
            string nickname = txt_nickname.Text.Trim();
            string remark = txt_remark.Text.Trim();

            // 检查用户名是否为空
            if (string.IsNullOrEmpty(username))
            {
                MessageBox.Show("用户名不能为空！", "提示");
                return;
            }

            // 检查昵称是否为空
            if (string.IsNullOrEmpty(nickname))
            {
                MessageBox.Show("昵称不能为空！", "提示");
                return;
            }

            // 2. 先检查用户名是否存在
            if (userBLL.CheckUserIsExist(username))
            {
                MessageBox.Show("该用户名已存在，请更换一个！", "提示");
                return;
            }

            // 3. 构造 UserModel 对象
            UserModel user = new UserModel
            {
                UserName = username,
                NickName = nickname,
                Remark = remark,
                UserIdentity = radioButton_manage.Checked ? 1 : 2,
                UserStatus = 1,   // 默认状态为正常
                IsDelete = 0      // 默认未删除
            };

            // 4. 执行插入操作
            int result = userBLL.InserUser(user);

            // 5. 判断结果并反馈给用户
            if (result > 0)
            {
                MessageBox.Show("添加用户成功！", "提示");
                this.Close();
                ReLoadList?.Invoke(); // 刷新主界面列表
            }
            else
            {
                MessageBox.Show("添加失败，请重试！", "提示");
            }
        }
        /// <summary>
        /// xiugai用户
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void UpdateUser()
        {
            // 获取当前编辑的用户对象
            UserModel user = userBLL.GetUserById(typeModel.FId);

            string newUsername = txt_username.Text.Trim();
            string newNickName = txt_nickname.Text.Trim();
            string newRemark = txt_remark.Text.Trim();

            #region 输入验证

            // 检查用户名是否为空
            if (string.IsNullOrEmpty(newUsername))
            {
                MessageBox.Show("用户名不能为空！", "提示");
                return;
            }

            // 检查昵称是否为空
            if (string.IsNullOrEmpty(newNickName))
            {
                MessageBox.Show("昵称不能为空！", "提示");
                return;
            }

            // 检查用户名是否已被其他用户使用（排除自己）
            if (userBLL.IsUsernameExists(newUsername,user.UserId))
            {
                MessageBox.Show("该用户名已被其他用户使用，请更换一个！", "提示");
                return;
            }

            #endregion

            #region 判断是否有实际修改

            bool hasChanges = false;

            if (user.UserName != newUsername)
            {
                user.UserName = newUsername;
                hasChanges = true;
            }

            if (user.NickName != newNickName)
            {
                user.NickName = newNickName;
                hasChanges = true;
            }

            if (user.Remark != newRemark)
            {
                user.Remark = newRemark;
                hasChanges = true;
            }

            int newIdentity = radioButton_manage.Checked ? 1 : 2;
            if (user.UserIdentity != newIdentity)
            {
                user.UserIdentity = newIdentity;
                hasChanges = true;
            }

            if (!hasChanges)
            {
                MessageBox.Show("您未做任何修改，无需保存。", "提示");
                return;
            }

            #endregion

            #region 执行更新操作

            if (userBLL.UpdateUser(user))
            {
                MessageBox.Show("修改用户成功！", "提示");
                this.Close();
                ReLoadList?.Invoke(); // 刷新主界面列表
            }
            else
            {
                MessageBox.Show("修改用户失败，请重试！", "提示");
            }

            #endregion
        }
    }
}
